import React, {
    PureComponent
} from 'react';

import {
    AppState
} from 'react-native';

import LoginStatus from './loginStatus';
import connect from './../../utils/connect';

import * as fcm from './../../utils/fcm';
import * as Event from './../../utils/event';

import userAction from './../../state/actions/user';
import chatAction from './../../state/actions/chat';
import commonAction from './../../state/actions/common';

import * as chatTypes from './../../state/types/chat';
import * as userTypes from './../../state/types/user';
import * as commonTypes from './../../state/types/common';

interface User {
    loginUser: any
}

interface Props {
    user: User,
    userActions:any,
    chatActions:any
    commonActions:any
}

@connect([`user`], {
    userActions:userAction,
    chatActions:chatAction,
    commonActions: commonAction
})
class Launch extends PureComponent<Props> {

    static defaultProps={
        user:{},
        userActions:{},
        chatActions:{},
        commonActions:{}
    }

    get commonActions() {
        const {
            commonActions
        } = this.props;
        return commonActions;
    }

    get chatActions() {
        const {
            chatActions
        } = this.props;
        return chatActions;
    }

    get userActions() {
        const {
            userActions
        } = this.props;
        return userActions;
    }

    get loginUser() {
        const {
            user
        } = this.props;
        const {
            loginUser = {}
        } = user;
        return loginUser;
    }

    get userId() {
        const {
            userId = 0
        } = this.loginUser;
        return userId;
    }

    get loginStatus() {
        return !!this.userId;
    }

    UNSAFE_componentWillMount() {
        Event.add(
            Event.ON_USER_LOGIN,
            this.onLoginLaunch
        )
        Event.add(
            Event.ON_USER_OUT,
            this.onLoginOut
        )
    }

    private onLoginLaunch = () => {
       this.updateDoData();
       AppState.addEventListener(
           'change',this.appStateChange
       )
    }

    private appStateChange = (type:string) => {
        if(type !== `active`) return false;
        this.updateDoData();
    }

    private updateDoData = () => {
        this.userActions[userTypes.loginUser]();
        this.commonActions[commonTypes.getCommonData]();
        this.chatActions[chatTypes.getServerUnreadMsg](this.userId);
    }

    private onLoginOut = () => {
        AppState.removeEventListener(
            'change',this.appStateChange
        )
    }

    componentDidMount() {
        fcm.init();
    }

    render() {
        return this.loginStatus && (
            <LoginStatus />
        )
    }
}

export default Launch;